package com.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exam.entity.po.Role;
import com.exam.entity.po.User;
import com.exam.entity.vo.Result;
import com.exam.service.RoleService;
import com.exam.service.UserService;
import com.exam.util.RedisUtil;
import com.exam.util.SaltEncryption;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @Des 管理员api接口
 * @Author ymj
 * @Date 2021/9/6 13:30
 */
@RestController
@CrossOrigin
@RequestMapping("/demo/admin")
@Slf4j
@Api(tags = "管理员相关接口", description = "提供管理员相关的API接口")
public class AdminController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @GetMapping("/getRole")
    @ApiOperation("查询系统权限信息")
    public Result getRole() {
        if (redisUtil.get("roleList") != null) {
            return Result.success(redisUtil.get("roleList"));
        } else {
            List<Role> userRoles = roleService.list(null);
            redisUtil.set("roleList", userRoles, 60 * 10 + new Random().nextInt(5) * 60);
            return Result.success(userRoles);
        }
    }
    @GetMapping("/getUserInfo")
    @ApiOperation("分页查询用户信息---查询条件(可无)(username,trueName),必须有的(pageNo,pageSize)")
    public Result getUserInfo(@RequestParam(required = false) String username,
                              @RequestParam(required = false) String name,
                              Integer pageNo, Integer pageSize) {
        IPage<User> userPage = new Page<>(pageNo, pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (!username.equals("") && username != null) wrapper.like("username", username);
        if (!name.equals("") && name != null) wrapper.like("name", name);
        userPage = userService.page(userPage, wrapper);
        List<User> userList = userPage.getRecords();
        Map<Object, Object> result = new HashMap<>();
        result.put("userList", userList);
        result.put("total", userPage.getTotal());
        return Result.success(result);
    }

    @GetMapping("/updateUserStatus/{type}")
    @ApiOperation("管理员操作用户: type=1(启用) 2(禁用) 3(删除) userIds(需要操作的用户id)")
    public Result updateUserStatus(@PathVariable("type") Integer type, String userIds) {
        String[] ids = userIds.split(",");
        if (type == 1) {
            for (String id : ids) {
                User user = userService.getById(Integer.parseInt(id));
                user.setStatus(1);
                userService.update(user, new UpdateWrapper<User>().eq("id", Integer.parseInt(id)));
                redisUtil.set("user:"+user.getUsername(),user,60 * 60 * 10 + new Random().nextInt(5) * 60 * 60);
            }
            return Result.success();
        } else if (type == 2) {
            for (String id : ids) {
                User user = userService.getById(Integer.parseInt(id));
                user.setStatus(2);
                userService.update(user, new UpdateWrapper<User>().eq("id", Integer.parseInt(id)));
                redisUtil.set("user:"+user.getUsername(),user,60 * 60 * 10 + new Random().nextInt(5) * 60 * 60);
            }
            return Result.success();
        } else if (type == 3) {
            for (String id : ids) {
                userService.removeById(Integer.parseInt(id));
            }
            redisUtil.set("userList",userService.list());
            return Result.success();
        }
        return Result.error("操作有误");
    }
    @PostMapping("/addUser")
    @ApiOperation("管理员新增用户")
    public Result addUser(@RequestBody User user) throws NoSuchAlgorithmException {
        List<User> userList = (List<User>) redisUtil.get("userList");
        if (userList==null){
            userList = userService.list();
        }
        for (int i=0;i<userList.size();i++){
            if (user.getUsername().equals(userList.get(i).getUsername())){
                return Result.error("用户名重复");
            }
        }
        String salt = UUID.randomUUID().toString().substring(0, 6);
        String newPwd = SaltEncryption.saltEncryption(user.getPassword(), salt);
        user.setPassword(newPwd);
        user.setSalt(salt);
        if (userService.save(user)){
            userList = userService.list();
            redisUtil.set("users",userList,60 * 60 * 10 + new Random().nextInt(5) * 60 * 60);
            return Result.success();
        }
        return Result.error("用户添加失败");
    }
}
